# -*- coding: UTF-8 -*-
# ---------------------------------------------------------
# @Author : Bingo
# @Time   : 2021/7/14 0:31
# @File   : 注册表.py  
# ---------------------------------------------------------
# There is no bug, have a great day. Please start your code.
import winreg
from datetime import datetime as dt


class ProxyWinreg:

    __instance = None

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self, **kwargs):
        self.root_key_path = winreg.HKEY_CURRENT_USER
        self.proxy_key_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings"
        self.proxy_enable = False
        try:
            self.key = winreg.OpenKey(self.root_key_path, self.proxy_key_path, 0, winreg.KEY_ALL_ACCESS)
            self.debug_print("加载配置环境成功...")
        except OSError as e:
            self.debug_print("加载注册表[HKEY_CURRENT_USER\\%s]失败，%s" % (self.proxy_key_path, e))

    @staticmethod
    def debug_print(msg):
        current_time = dt.now().time().__format__("%H:%M:%S")
        info = "[%s]>>>: %s" % (current_time, msg)
        print(info)

    def get_proxy_enable(self):
        try:
            value, key_type = winreg.QueryValueEx(self.key, "ProxyEnable")
            return value
        except Exception as e:
            self.debug_print(str(e))
            return None

    def get_proxy_server(self):
        try:
            value, key_type = winreg.QueryValueEx(self.key, "ProxyServer")
            return value
        except Exception as e:
            self.debug_print(str(e))
            return None

    def get_proxy_override(self):
        try:
            value, key_type = winreg.QueryValueEx(self.key, "ProxyOverride")
            return value
        except Exception:
            return None

    def set_proxy_enable(self, enable):
        try:
            winreg.SetValueEx(self.key, "ProxyEnable", 0, winreg.REG_DWORD, enable)
            self.proxy_enable = True
        except Exception as e:
            self.debug_print("开始代理失败：" + str(e))

    def set_proxy_server(self, server_ip, port):
        try:
            winreg.SetValueEx(self.key, "ProxyServer", 0, winreg.REG_SZ, "%s:%s" % (server_ip, port))
        except Exception as e:
            self.debug_print("设置代理服务器失败：" + str(e))

    def set_proxy_override(self, ignore_list):
        try:
            winreg.SetValueEx(self.key, "ProxyOverride", 0, winreg.REG_SZ, ";".join(ignore_list))
        except Exception as e:
            self.debug_print("设置代理例外失败：" + str(e))

    def query_proxy_status(self):
        proxy_enable = self.get_proxy_enable()
        if proxy_enable == 1:
            self.proxy_enable = True
            proxy_server = self.get_proxy_server()
            proxy_override = self.get_proxy_override()
            self.debug_print("当前BP工具代理开启，代理Server【%s】,代理Override【%s】" % (proxy_server, proxy_override))
            return
        self.debug_print("当前BP工具代理关闭")

    def set_bp_proxy_on(self):
        self.set_proxy_enable(1)
        self.set_proxy_server("127.0.0.1", "8080")
        self.set_proxy_override([])

    def set_bp_proxy_off(self):
        self.set_proxy_enable(0)

    def show_help_info(self):
        info = "开启BP代理【1】，关闭BP代理【0】，退出【q】, 配置代理服务器【s】，配置代理服务器例外【o】..."
        self.debug_print(info)

    def main(self):
        self.query_proxy_status()
        self.debug_print("开启BP代理【1】，关闭BP代理【0】，退出【q】...")
        while True:
            in_command = input("请输入命令：")
            if in_command not in ["0", "1", "q", "Q", "h", "H", "s", "S", "o", "O"]:
                self.debug_print("输入命令无效！")
                continue
            if in_command == "0":
                self.set_bp_proxy_off()
            elif in_command == "1":
                self.set_bp_proxy_on()
            elif in_command in ["Q", "q"]:
                self.debug_print("退出程序！同时关闭代理")
                self.set_bp_proxy_off()
                break
            elif in_command in ["h", "H"]:
                self.show_help_info()
            elif in_command in ["s", "S"]:
                try:
                    server, port = input("配置代理服务器，输入代理服务器IP和端口，空格隔开：").split(" ")
                    self.set_proxy_server(server, port)
                except Exception as e:
                    self.debug_print("输入有误！")
                    continue
            elif in_command in ["o", "O"]:
                ignore_list = input("配置代理服务器, 输入例外服务器IP，空格隔开：").split(" ")
                self.set_proxy_override(ignore_list)
            if in_command in ["0", "1", "s", "S", "o", "O"]:
                self.query_proxy_status()


if __name__ == "__main__":
    p1 = ProxyWinreg()
    p1.main()

# debug_print("hsauhsa")
# path = "SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings"
# key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0, winreg.KEY_ALL_ACCESS)
# s = winreg.QueryValueEx(key, "ProxyEnable")
# winreg.SetValueEx(key, "ProxyEnable", 0, winreg.REG_DWORD, False)
# # winreg.FlushKey(key)
# print(s)
